<?php
/**
 * 微信公众号直接接口文件
 * 用于通过直接URL访问方式接收微信消息
 * 使用方法：在微信公众平台上设置URL为 https://www.yourdomain.com/wp-content/plugins/hywl-wechat/wechat-direct.php
 */

// 加载WordPress环境
define('WP_USE_THEMES', false);
// 修复路径引用问题 - 多种方式尝试加载 wp-load.php
$wp_load_paths = array(
    dirname(dirname(dirname(__FILE__))) . '/wp-load.php',
    $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php',
    '/www/wwwroot/www.ailingxi.cn/wp-load.php' // 硬编码绝对路径作为最后手段
);

$loaded = false;
foreach ($wp_load_paths as $path) {
    if (file_exists($path)) {
        require_once($path);
        $loaded = true;
        // 记录成功加载的路径到文件
        file_put_contents(__DIR__ . '/logs/path_debug.log', date('Y-m-d H:i:s') . ' - Loaded: ' . $path . "\n", FILE_APPEND);
        break;
    }
}

if (!$loaded) {
    // 记录所有尝试过的路径
    $debug_msg = date('Y-m-d H:i:s') . " - Failed to load wp-load.php, tried:\n";
    foreach ($wp_load_paths as $path) {
        $debug_msg .= "- $path (exists: " . (file_exists($path) ? 'yes' : 'no') . ")\n";
    }
    file_put_contents(__DIR__ . '/logs/path_debug.log', $debug_msg, FILE_APPEND);
    
    die('无法加载WordPress环境，请联系管理员检查路径配置。');
}

// 设置日志路径
$log_file = __DIR__ . '/logs/direct.log';

// 记录日志函数
function direct_log($message) {
    global $log_file;
    $log_message = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
    file_put_contents($log_file, $log_message, FILE_APPEND);
}

// 记录请求信息
direct_log('收到直接请求：' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI']);
direct_log('请求头: ' . json_encode(getallheaders(), JSON_UNESCAPED_UNICODE));
direct_log('GET参数: ' . json_encode($_GET, JSON_UNESCAPED_UNICODE));

// 服务器验证处理
if (isset($_GET['echostr'])) {
    direct_log('收到验证请求，echostr=' . $_GET['echostr']);
    
    // 获取微信公众号设置
    $options = get_option('hywl_wechat_options', array());
    $token = isset($options['token']) ? $options['token'] : '';
    
    direct_log('使用Token: ' . $token);
    
    // 验证签名
    $signature = isset($_GET['signature']) ? $_GET['signature'] : '';
    $timestamp = isset($_GET['timestamp']) ? $_GET['timestamp'] : '';
    $nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
    $echostr = isset($_GET['echostr']) ? $_GET['echostr'] : '';
    
    if (empty($signature) || empty($timestamp) || empty($nonce) || empty($echostr)) {
        direct_log('验证参数不完整');
        exit('Invalid request');
    }
    
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);
    
    direct_log('计算的签名: ' . $tmpStr . ', 微信签名: ' . $signature);
    
    if ($tmpStr == $signature) {
        direct_log('验证成功，返回echostr: ' . $echostr);
        echo $echostr;
    } else {
        direct_log('验证失败，签名不匹配');
        echo 'Failed to verify signature';
    }
    exit;
}

// 处理消息
// 接收消息内容
$postStr = file_get_contents('php://input');
direct_log('接收原始POST数据: ' . (empty($postStr) ? '空' : $postStr));

if (empty($postStr)) {
    direct_log('未接收到消息内容');
    exit('Empty request');
}

// 创建HYWL_Wechat对象处理消息
if (class_exists('HYWL_Wechat')) {
    direct_log('通过HYWL_Wechat类处理消息');
    $hywl_wechat = new HYWL_Wechat();
    $hywl_wechat->handle_request();
} else {
    direct_log('错误：HYWL_Wechat类不存在');
    // 简单响应，防止微信服务器重试
    echo '<xml>
        <ToUserName><![CDATA['.htmlspecialchars($postObj->FromUserName).']]></ToUserName>
        <FromUserName><![CDATA['.htmlspecialchars($postObj->ToUserName).']]></FromUserName>
        <CreateTime>'.time().'</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[系统正在维护中，请稍后再试。]]></Content>
    </xml>';
}

direct_log('请求处理完成');
